#include "open_save.h"


char* Open(/*HWND hwnd*/)
{
	OPENFILENAME ofn;       // common dialog box structure
	char szFile[5000]; 
	

	// Initialize OPENFILENAME
	ZeroMemory(&ofn, sizeof(ofn));
	ofn.lStructSize = sizeof(ofn);
	/*ofn.hwndOwner = hwnd;*/
	ofn.lpstrFile = szFile;
	ofn.lpstrFile[0] = '\0';
	ofn.nMaxFile = sizeof(szFile);
	ofn.lpstrFilter = "*.$$$";                         
	ofn.nFilterIndex = 1;
	ofn.lpstrFileTitle = NULL;
	ofn.nMaxFileTitle = 0;
	ofn.lpstrInitialDir = NULL;
	ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;

	// Display the Open dialog box. 
	GetOpenFileName(&ofn);

	return ofn.lpstrFile;
}

char* Save(/*HWND hwnd*/)
{
	OPENFILENAME ofn;       // common dialog box structure
	char szFile[5000];       
             

	// Initialize OPENFILENAME
	ZeroMemory(&ofn, sizeof(ofn));
	ofn.lStructSize = sizeof(ofn);
	/*ofn.hwndOwner = hwnd;*/
	ofn.lpstrFile = szFile;
	ofn.lpstrFile[0] = '\0';
	ofn.nMaxFile = sizeof(szFile);
	ofn.lpstrFilter = "*.$$$";                         
	ofn.nFilterIndex = 1;
	ofn.lpstrFileTitle = NULL;
	ofn.nMaxFileTitle = 0;
	ofn.lpstrInitialDir = NULL;
	ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
	
	// Display the Save dialog box. 
	GetSaveFileName(&ofn);

	return ofn.lpstrFile;
}

void SaveToFile(Stack<shape *> redo,HWND hwnd)
{
	char *path;
	int objectType,objectSize;
	FILE *file;
	Stack<shape *> temp;
	shape *s;

	path=Save(/*hwnd*/);
	file = fopen(path,"w+b");
	while(!redo.Empty())
	{
		s = redo.Pop();
		objectType=s->GetClassID();
		switch(objectType)
		{
		case 1:
			objectSize = sizeof(rect);
			break;
		case 2:
			objectSize = sizeof(square);
			break;
		case 3:
			objectSize = sizeof(ellipse);
			break;
		case 4:
			objectSize = sizeof(circle);
			break;
		case 5:
			objectSize = sizeof(line);
			break;
		}
		fwrite(&objectType,sizeof(int),1,file);
		fwrite(s,objectSize,1,file);
		temp.Push(s);
		s->Hide(hwnd);
	}
	fclose(file);

	while(!temp.Empty())
		redo.Push(temp.Pop());
}

void OpenFromFile(HWND hwnd,Stack<shape *> redo,Stack<shape *> undo)
{
	char *path;
	FILE *file;
	shape *s,*p;
	int objectSize,objectType;

	path=Open(/*hwnd*/);
	while(!redo.Empty())
	{
		p=redo.Pop();
		p->Hide(hwnd);
	}
	while(!undo.Empty())
	{
		undo.Pop();
	}
	file = fopen(path,"r+b");
	while(fread(&objectType,sizeof(int),1,file))
	{
		switch(objectType)
		{
		case 1:
			objectSize = sizeof(rect);
			s=new rect;
			break;
		case 2:
			objectSize = sizeof(square);
			s=new square;
			break;
		case 3:
			objectSize = sizeof(ellipse);
			s=new ellipse;
			break;
		case 4:
			objectSize = sizeof(circle);
			s=new circle;
			break;
		case 5:
			objectSize = sizeof(line);
			s=new line;
			break;
		}
		fread(s,objectSize,1,file);
		s->Draw(hwnd);
	}
	fclose(file);
}



